<?php

namespace App\Http\Controllers\Company;

use App\Http\Controllers\Controller;
use App\Models\ClassModel;
use App\Models\CourseArrangeModel;
use App\Models\ClassCourseModel;
use App\Models\CourseArrangeLogModel;
use App\Models\StudentSignModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Services\CourseService;

class CourseArrangeController extends Controller
{
    public function add(Request $request) {
        // 在相同一个时间段，教室，老师不能重复排课
        $time = $request->time;
        $hour = substr($time, 0, 2);
        
        // 根据不同的排课类型，获得需要排课的日期
        $dates = $request->dates;
        $arrangeType = $request->type;
        if ($arrangeType !== 'date') {
            $dates = [];
            $startTime = strtotime($request->start_date);
            $endTime = strtotime($request->end_date);
            $weekDays = $request->weeks;
            while ($startTime <= $endTime) {
                $date = date('Y-m-d', $startTime);
                $startTime = strtotime('+1 day', $startTime);
                if ($arrangeType == 'day') {
                    $dates[] = $date;
                    continue;
                }

                if ($arrangeType == 'week') {
                    $week = date('w', strtotime($date));
                    if (in_array($week, $weekDays)) {
                        $dates[] = $date;
                    }
                }
            }
        }
        $classCourse = ClassCourseModel::find($request->course);
        foreach ($dates as $date) {

            //1.判断在该时段 该班级是否有排课
            $hasCourse = CourseArrangeModel::where('date', $date)
            ->where('time', 'like', $hour.'%')
            ->where('class_id', $request->class)
            ->where('course_id', $classCourse->course_id)
            ->first();
            if ($hasCourse) {
                return self::err('该班级在本时段已对该课程进行排课');
            }
            //2.检查在该时段，该教室是否被占用
            //3.检查在该时段，该老师是否被占用
        }
       
        // 添加排课日志
        $log = CourseArrangeLogModel::create([
            'company_id' => $request->company_id,
            'type' => $arrangeType,
            'dates' => json_encode($dates),
            'time' => $time,
            'class_id' => $request->class,
            'course_id' => $classCourse->course_id,
            'teacher_id' => $classCourse->teacher_id,
            'room_id' => $request->room,
            'start_date' => $request->start_date,
            'end_date' => $request->end_date,
            'weeks' => json_encode($request->weeks),
            'course_num' => $request->course_num,
        ]);
        
        $data = [
            'company_id' => $request->company_id,
            'room_id' => $request->room,
            'class_id' => $request->class,
            'course_id' => $classCourse->course_id,
            'teacher_id' => $classCourse->teacher_id,
            'time' => $time,
            'course_num' => $request->course_num,
            'total_course_money' => 0,
            'arrange_log_id' => $log->id,
        ];

        foreach ($dates as $date) {
            $data['date'] = $date;
            CourseArrangeModel::create($data);
        }
        return self::sendOk();
    }

    public function list(Request $request) {
        $startDate = $request->startDate;
        // 获取一周的日期
        $weekDays = [];
        for ($i = 0; $i < 7; $i++) {
            $date = date('Y-m-d', strtotime($startDate . ' +' . $i . ' days'));
            $weekDays[] = $date;
        }

        // 获取这段日期的排课信息
        // $query = DB::table('course_arrange as a')
        // ->leftJoin('class as b', 'a.class_id', '=', 'b.id')
        // ->leftJoin('class_course as cc', 'a.class_course_id', '=', 'cc.id')
        // ->leftJoin('room as d', 'a.room_id', '=', 'd.id')
        // ->where('a.company_id', $request->company_id)
        // ->whereIn('a.date', $weekDays);
        
        
        $query = CourseArrangeModel::where('company_id', $request->company_id)
        ->whereIn('date', $weekDays)
        ->with('class')
        ->with('room')
        ->with('course')
        ->with('teacher');

        if ($request->room) 
            $query->where('room_id', $request->room);

        if ($request->class) 
            $query->where('class_id', $request->class);

        if($request->teacher) 
            $query->where('teacher_id', $request->teacher);

        $arranges = $query->get();

        // 整理数据
        // dates: [
        //     {
        //         day: '05/05',
        //         week: '星期一',
        //         num: 2
        //     }
        // ],
        // times: [
        //     {
        //         time: '08:00',
        //         days: [
        //             [{ name: '课程1', teacher: '教师1' }, { name: '课程2', teacher: '教师2' }],
        //             [],
        //             [],
        //             [],
        //             [{ name: '课程10', teacher: '教师10' }],
        //             [],
        //             [{ name: '课程13', teacher: '教师13' }, { name: '课程14', teacher: '教师14' }]
        //         ]
        //     }
        // ]
        $dates = [];
        $times = [];
        foreach($weekDays as $weekDay) {
            $date = date('m/d', strtotime($weekDay));
            $week = date('w', strtotime($weekDay));
            $weekArr = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
            $key = 'd' . str_replace('-', '', $weekDay);
            $dates[$key] = [
                'day' => $date,
                'week' => $weekArr[$week],
                'num' => 0
            ];
        }
       
        for($i = 8; $i < 21; $i++) {
            $time = $i < 10 ? '0'.$i.':00' : $i.':00';
            $timeKey = 't'. str_replace(':00', '', $time);
            $times[$timeKey] = [
                'time' => $time,
                'days' => []
            ];
            foreach ($weekDays as $weekDay) {
                $dateKey = 'd'. str_replace('-', '', $weekDay);
                $times[$timeKey]['days'][$dateKey] = [];
            }
        }

        foreach ($arranges as $arrange) {
            $dateKey = 'd'. str_replace('-', '', $arrange->date);
            $timeKey = 't'. substr($arrange->time, 0, 2);
            $dates[$dateKey]['num']++;
            $times[$timeKey]['days'][$dateKey][] = [
                'id' => $arrange->id,
                'class' => $arrange->class->name,
                'teacher' => $arrange->teacher->name,
                'room' => $arrange->room->name,
                'time' => $arrange->time,
                'status' => $arrange->status,
            ];
        }

        // return self::sendOk([
        //     'dates' => $dates,
        //     'times' => $times
        // ]);
        // 重新组织数据
        $newDates = [];
        $newTimes = [];
        foreach ($weekDays as $weekDay) {
            $dateKey = 'd'. str_replace('-', '', $weekDay);
            $newDates[] = $dates[$dateKey];
        }

        $timeIndex = 0;
        for ($i = 8; $i < 21; $i++) {   
            $timeKey = 't'. str_replace(':00', '', $i < 10? '0'.$i.':00' : $i.':00');
            $newTimes[$timeIndex] = ['time' => $times[$timeKey]['time'], 'days' => []];
            $dateIndex = 0;
            foreach ($weekDays as $weekDay) {
                $dateKey = 'd'. str_replace('-', '', $weekDay);
                $newTimes[$timeIndex]['days'][$dateIndex] = $times[$timeKey]['days'][$dateKey];
                $dateIndex++;
            }
            $timeIndex++;
        }
        
        return self::sendOk([
            'dates' => $newDates,
            'times' => $newTimes
        ]);
    }

    public function delete(Request $request) {
        CourseArrangeModel::where('id', $request->id)->where('company_id', $request->company_id)->delete();
        return self::sendOk();
    }

    public function logs(Request $request) {
        $logs = CourseArrangeLogModel::where('company_id', $request->company_id)
            ->with('class')
            ->with('room')
            ->with('course')
            ->with('teacher')
            ->orderBy('id', 'desc')
            ->limit(20)->get();
        return self::ok($logs);
    }

    // 撤销排课
    public function revoke(Request $request) {
        $id = $request->id;
        $log = CourseArrangeLogModel::find($id);
        CourseArrangeModel::where('arrange_log_id', $log->id)->delete();
        $log->delete();
        return self::ok();
    }
    private const SIGN_RESULT = [ '未签到', '正常', '迟到', '请假', '旷课' ];
    // 签到记录
    public function signLogs(Request $request) {
        $arrangeCourse = CourseArrangeModel::find($request->arrangeCourseId);
        $students = DB::table('class_student as a')
        ->leftJoin('student as b', 'a.student_id', '=', 'b.id')
        ->leftJoin('student_sign as c', function($join) use ($arrangeCourse) {
            $join->on('c.student_id', '=', 'a.student_id')
                ->where('c.arrange_id', '=', $arrangeCourse->id);
                // ->where('c.class_id', '=', $arrangeCourse->class_id)
                // ->where('c.course_id', '=', $arrangeCourse->course_id)
                // ->where('c.date', '=', $arrangeCourse->date)
                // ->where('c.time', '=', $arrangeCourse->time);
        })
        ->select('a.student_id', 'b.name as student_name', 'c.course_num', 'c.result as sign_result', 'c.created_at')
        ->where('a.class_id', $arrangeCourse->class_id)
        ->where('b.deleted_at', null)
        ->where('a.deleted_at', null)
        ->get();

        foreach ($students as $student) {
            $student->sign_result = $student->sign_result ?: 0;
            $student->sign_result_text = self::SIGN_RESULT[$student->sign_result];
        }
        return self::ok($students);
    }

    // 签到
    public function sign(Request $request) {
        $studentId = $request->studentId;
        $result = $request->result;
        $courseNum = $request->courseNum;
        $arrangeCourseId = $request->arrangeCourseId;
        $arrangeCourse = CourseArrangeModel::find($arrangeCourseId);
        $res = CourseService::sign($arrangeCourseId, $arrangeCourse->course_id, $studentId, $result, $courseNum, true);
        return $res === true ? self::ok() : self::err($res);
    }
}
